import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import profileIndex from '../views/profile/Index.vue'
import Proedit from '../views/profile/Proedit.vue'
import Test from '../views/Test.vue'
import profileFollow from '../views/profile/Follow.vue'
import ArticleDetail from '../views/ArticleDetail.vue'
import ProfileStar from '../views/profile/Star.vue'
import MoreComment from '../views/MoreComment.vue'
import MyComment from '../views/profile/MyComment.vue'
import Search from '../views/Search.vue'
import Manage from '../views/Manage.vue'


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/profile',
    name: 'profileIndex',
    component: profileIndex,
    meta: {
      needAuth: true
    }
  },
  {
    path: '/proedit',
    name: 'Proedit',
    component: Proedit,
    meta: {
      needAuth: true
    }
  },
  {
    path: '/test',
    name: 'Test',
    component: Test
  },
  {
    path: '/follow',
    component: profileFollow,
    meta: {
      needAuth: true
    }
  },
  // 获取文章详情：
  {
    path: '/articledetail/:id',
    // path: '/articledetail',
    component: ArticleDetail,
  },
  {
    path: '/profilestar',
    component: ProfileStar,
    meta: {
      needAuth: true
    }
  },
  {
    path: '/morecomment/:id',
    name: 'MoreComment',
    component: MoreComment,
  },
  {
    path: '/mycomment',
    name: 'MyComment',
    component: MyComment,
    meta: {
      needAuth: true
    }
  },
  {
    path: '/search',
    name: 'Search',
    component: Search,
    // meta: {
    //   needAuth: true
    // }
  },
  {
    path: '/manage',
    name: 'Manage',
    component: Manage
  }
]

const router = new VueRouter({
  routes,
  // mode: 'history' 可设置哈希路由，但是必须和后端发起请求的url一致！否则易出现404错误！
})

// 添加全局路由守卫：
router.beforeEach((to, from, next) => {

  // 当进入的页面是个人中心：
  // 1、第一种方法：添加逻辑或：
  // if (to.path == '/profile' || to.path == '/proedit') {
  // 2、第二种方法：定义一个需要校验的数组：
  // const pagesNeedAuth = [
  //   '/profile',
  //   '/proedit'
  // ]
  // // 如果存在则为1或0，不存在则为-1：
  // if (pagesNeedAuth.indexOf(to.path) > -1) {

  console.log('看看当前页面的原信息是什么？')
  console.log(to.meta);
  // 3、第三种方法：
  // 给需要的页面元素添加meta属性

  if (to.meta.needAuth) {
    // 判断token是否存在：
    if (localStorage.getItem('token')) {
      // 如果有token就放行：
      return next();
    } else {
      // 不存在？就跳转到登录页：
      return router.push('/login').catch((err) => {
      })
    }
  }
  return next();
})

export default router
